package com.gxa.controller;

import com.alibaba.fastjson.JSON;
import com.gxa.pojo.Permission;
import com.gxa.pojo.Store;
import com.gxa.service.PermissionService;
import com.gxa.utils.JsonResult;
import com.gxa.utils.PowerTreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/permission")
@CrossOrigin
public class PermissionController {

    @Autowired
    PermissionService permissionService;

    JsonResult jsonResult;

    @ResponseBody
    @RequestMapping("/findPermissionByUserName")
    public Map findPermissionByUserName(@RequestBody Map map){
        jsonResult =new JsonResult();
        String userName = map.get("userName").toString();
        System.out.println(userName);
        List<Permission> permissions = permissionService.findPermissionByUserName(userName);
        List<Permission> allPermission = permissionService.findAllPermission();
        System.out.println(allPermission);
        List<Permission> treeList = PowerTreeUtil.getTreeList(permissions);
        System.out.println(treeList);
        jsonResult.put("allPermission",allPermission);
        jsonResult.setData(treeList);
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        return jsonResult.getValues();
    }


    @ResponseBody
    @RequestMapping("/insertRolePermission")
    public Map insertRolePermission(@RequestBody List<Map> map){
        jsonResult=new JsonResult();
        System.out.println(map);
        System.out.println(map.size());
        Map map1 = map.get(0);
        if (map1.get("roleID").toString()!=null){
            String roleID = map1.get("roleID").toString();
            Integer integer1 = permissionService.deleteRolePermission(Integer.valueOf(roleID));
        }
        if (map.size()==1){
            String roleID = map1.get("roleID").toString();
            Integer integer1 = permissionService.deleteRolePermission(Integer.valueOf(roleID));
            return jsonResult.getValues();
        }
        Integer integer = permissionService.insertRolePermission(map);
        if (integer>0){
            jsonResult.setCode("200");
            jsonResult.setMsg("添加成功");
        }else {
            jsonResult.setCode("406");
            jsonResult.setMsg("失败");
        }
        return jsonResult.getValues();
    }

}